package com.jwd.avmanager.parse;

import com.alibaba.fastjson.JSON;
import com.jwd.avmanager.cache.BasicCache.EnumCacheManager;
import com.jwd.avmanager.constant.Cmd;
import com.jwd.avmanager.entity.*;
import com.jwd.avmanager.pojo.*;
import com.jwd.avmanager.repository.BDMybais;
import com.jwd.avmanager.server.ClientManager;
import com.jwd.avmanager.util.*;

import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import jdk.nashorn.internal.ir.CallNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * @ProjectName: avmanager
 * @Desc: 协议解析器，解析客户端协议并完成相关业务处理
 * @Author: david
 * @Date: 2022/2/21
 */
public class ProtocolParser {
    Logger logger = LoggerFactory.getLogger(ProtocolParser.class);

    private ChannelHandlerContext ctx;
    private ProtocolAnalysis analysis;

    public ProtocolParser(ChannelHandlerContext handlerContext) {
        this.ctx = handlerContext;
        this.analysis = new ProtocolAnalysis();
    }

    /**
     * 解析协议
     *
     * @param packet 客户端发过来的消息
     */
    public void parseMessage(DecodePacket packet) {
        DebugLogger.info("parseMessage packet："+packet);
        //数据校验是否合法
        String clientId=null;
        if (Cmd.CMD_IN_LOGIN != packet.getCmdType() && Cmd.CMD_IN_LOGIN_V2 != packet.getCmdType()) {
             clientId = ClientManager.getInstance().getClientId(ctx);

            if (clientId == null) {
                DebugLogger.err(logger, "The message originated from an unregistered client.");// 消息来自未注册的客户端
                ctx.close();
                return;
            }
            Integer devIdx = packet.getDevIdx();
            if (devIdx == null || devIdx <= 0) {
                DebugLogger.err(logger, "devIdx == NULL");
                try {
                    byte[] fileNamebyte = "EXCEPTION_RESPONSE_0063".getBytes("gb2312");
                    ResponseFactory.ExceptionResponse(Cmd.CMD_OUT_EXCEPTION_RESPONSE,fileNamebyte,ctx,logger);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                return;
            }

        }

        switch (packet.getCmdType()) {
            case Cmd.CMD_IN_LOGIN:
                DebugLogger.info(logger,"收到登录指令 CMD_IN_LOGIN");
                //解析登录信令
                dealLogin(packet);
                break;
            case Cmd.CMD_IN_LOGIN_V2:
                DebugLogger.info(logger,"收到登录指令 CMD_IN_LOGIN_V2");
                //解析登录信令
                dealLogin_V2(packet);
                break;
            case Cmd.CMD_IN_HEARTBEAT_V2:
            case Cmd.CMD_IN_HEARTBEAT:
                //收到心跳指令
                DebugLogger.info(logger,"收到心跳指令:"+clientId);
                dealHeartbeat();
                break;
            case Cmd.CMD_IN_CANCEL_TERMINAL:
                //取消终端设备的注册
                DebugLogger.info(logger,"取消终端设备的注册:"+clientId);
                cancelDeviceRegister(packet);
                break;
            case Cmd.CMD_IN_REQUEST_GPS:
                //GPS上传
                DebugLogger.info(logger,"GPS上传:"+clientId);
                uploadGPS(packet);
                break;
            case Cmd.CMD_IN_SEND_EQUIPMENT_STATE:
                //发送设备端当前视频通话或者集群对讲的状态
                DebugLogger.info(logger,"发送设备端当前视频通话或者集群对讲的状态:"+clientId);
                SendEquipmentState(packet);
                break;
            case Cmd.CMD_IN_GET_SETVER_PORT:
                //发送设备端当前视频通话或者集群对讲的状态
                DebugLogger.info("获取目标的状态及服务器地址和端口号:"+clientId);
                getServerPort(packet);
                break;
            case Cmd.CMD_IN_TALKBACK_GROUP:
                //获取集群对讲群组列表
                DebugLogger.info("获取集群对讲群组列表:"+clientId);
                groupList(packet);
                break;
            case Cmd.CMD_IN_TALKBACK_PERSONNEL:
                //获取集群对讲人员列表
                DebugLogger.info("获取集群对讲人员列表:"+clientId);
                userList(packet);
                break;
            case Cmd.CMD_IN_CALL_PERSONNEL_LIST:
                //获取对讲组内通话人员列表
                DebugLogger.info("获取对讲组内通话人员列表:"+clientId);
                talkbackCallList(packet);
                break;
            case Cmd.CMD_IN_CALL_PERSONNEL_LIST2:
                //获取对讲组内通话人员列表
                DebugLogger.info("获取对讲组内通话人员列表:"+clientId);
                talkbackCallList(packet);
                break;
            case Cmd.CMD_IN_IEMI_REGISTER:
                DebugLogger.info("设备查询IEMI是否已经注册:"+clientId);
                tagIMEI(packet);
                break;
            case Cmd.CMD_IN_VIDEO_PERSONNEL_LIST:
//                DebugLogger.debug("视频通话用户列表");
//                voideoList(packet);
                DebugLogger.info("获取当前部门用户:"+clientId);
                getUsetDepList(packet);
                break;
            case Cmd.CMD_IN_TARGET_STATE:
                DebugLogger.info("获取目标的状态及WebRTC服务器地址和端口号:"+clientId);
                try {
                    TatgetState(packet);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                break;
            case Cmd.CMD_IN_JOIN_WEBRTC:
                DebugLogger.debug(logger,"加入WebRTC房间:"+clientId);
                try {
                    DebugLogger.info(new String(packet.getBody(), "GB2312").trim() + "房间号");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                break;
            case Cmd.CMD_IN_QUIT_WEBRTC:
                DebugLogger.info("退出TCWebRTC房间:"+clientId);
                String room = "";
                try {
                    room = new String(packet.getBody(), "GB2312").trim();
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                DebugLogger.info(room + "房间号CMD_IN_QUIT_WEBRTC");
                Integer userId = ClientManager.getInstance().getRtcRoom(room);
                Users user = BDMybais.getInstance().getUser(userId);
                if(user == null ){
                    DebugLogger.err(logger,"mysql get user data is null "+user);
                }
                ChannelHandlerContext socketClient = ClientManager.getInstance().getWebSocket(user.getuLoginName());
                String strMy = "{\"devID\":\"" + packet.getDevIdx() + "\",\"cmd\":\"" + Cmd.CMD_OUT_STOP_COLONY_TALKBACK + "\",\"value\":{}}";
                if (socketClient != null) {
                    ResponseSendUtil.writeAndFlushWs(strMy, socketClient);
                    ClientManager.getInstance().delRtcRoom(room);
                } else {
                    DebugLogger.err(logger, user.getuLoginName()+"<--user.getuLoginName()  socketClient ——CMD_IN_QUIT_WEBRTC is null ");
                }

                break;
            case Cmd.CMD_IN_SOS_EMERGENCY:
                //设备查询IEMI是否已经注册2
                DebugLogger.info("发送SOS紧急呼叫:"+clientId);
                emergencyCall2_1(packet);
//                try {
//                } catch (UnsupportedEncodingException e) {
//                    e.printStackTrace();
//                }
                break;
            case Cmd.CMD_IN_SOS_EMERGENCY_V2:
                //设备查询IEMI是否已经注册2
                DebugLogger.info("发送SOS紧急呼叫V2版本:"+clientId);
                emergencyCall1_1(packet);
//                try {
//                } catch (UnsupportedEncodingException e) {
//                    e.printStackTrace();
//                }
                break;
            case Cmd.CMD_IN_GET_FTP_SERVER:
                //获取获取ftp服务器参数
                DebugLogger.info("获取获取ftp服务器参数:"+clientId);
                try {
                    getFtpServer(packet);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                break;
            case Cmd.CMD_IN_UPLOADING_FILE:
                //提交上传成功的文件名
                DebugLogger.info("提交上传成功的文件名:"+clientId);
                try {
                    uploadingFile(packet);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                break;
            case Cmd.CMD_IN_EXAMINE_FILE:
                // 检查文件是否已经上传过
                DebugLogger.info(" 检查文件是否已经上传过:"+clientId);
                try {
                    examineFile(packet);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                break;
            case Cmd.CMD_IN_SEND_SHOOT_FILES:
                // 发送已经拍摄的文件列表
                DebugLogger.info(" 发送已经拍摄的文件列表 :"+clientId);
                sendShootFiles(packet);
                break;
            case Cmd.CMD_IN_GET_UPGRADE_FILE:
                // 发送已经拍摄的文件列表
                DebugLogger.info(" 发送已经拍摄的文件列表 :"+clientId);
                getUpgradeFile(packet);
                break;
            default:
                DebugLogger.err(logger,"未知信令_default_TCP" + packet.getCmdType());
                DebugLogger.err(logger,packet.toString());
                break;
        }
    }

    //设备端获取升级文件包
    private void getUpgradeFile(DecodePacket packet) {
        DebugLogger.err(logger,packet.getDevIdx()+ " <--packet Send the list of files that have been shot.");  //发送已经拍摄的文件列表
    }

    /**
     * 发送已经拍摄的文件列表
     *
     * @param packet
     */
    private void sendShootFiles(DecodePacket packet) {

        byte[] body = packet.getBody();
        String fileName = new String(body, StandardCharsets.UTF_8).trim();
        if(fileName == null){
          fileName ="";
        }
        String[] splitFiles = fileName.split("\\|");

        DebugLogger.info("fileName.size :"+splitFiles.length);
        CopyOnWriteArrayList<String> devFileMatching = ClientManager.getInstance().getDevFileMatching(packet.getDevIdx());
        // 如果获取的列表为空，则初始化一个新列表
        if (devFileMatching == null || devFileMatching.isEmpty()) {
            devFileMatching = new CopyOnWriteArrayList<>();
        }

        // 只有在splitFiles不为空时才进行处理
        if (splitFiles != null && splitFiles.length > 0) {
            // 将splitFiles中的文件名添加到列表中
            Collections.addAll(devFileMatching, splitFiles);

            // 更新到ClientManager
            //TODO 获取之前的列表然后追加  如果没有直接加入列表
            ClientManager.getInstance().setFileMatching(packet.getDevIdx(), devFileMatching);
        }
        //TODO 遍历调度台更具设备id拿到调度地址
// 发送给设备关联的所有用户
        ParserSend.sendFileList(packet.getDevIdx(),null, devFileMatching,
                ParserSend.SendTargetType.ALL_DEVICE_USERS, null);
    }

    /**
     * 服务器返回文件是否上传过
     *
     * @param packet
     * @throws UnsupportedEncodingException
     */
    private void examineFile(DecodePacket packet) throws UnsupportedEncodingException {
        String fileName = new String(packet.getBody(), StandardCharsets.UTF_8).trim();
        DebugLogger.info(packet.toString() + " -- " + fileName);
        BDMybais instance = BDMybais.getInstance();
        int fileCount = instance.getFileCount(fileName);
        DebugLogger.info("fileCount--->" + fileCount);

        byte[] bytes = new byte[200];
        byte[] fileNamebyte = fileName.getBytes("gb2312");
        System.arraycopy(fileNamebyte, 0, bytes, 0, fileNamebyte.length);

        byte[] listResponse = null;
        if (fileCount > 0) {
            listResponse = ResponseFactory.getListResponse(Cmd.CMD_OUT_FILE_UPLOADING, (short) 1, packet.getDevIdx(), bytes);
            Map<String, Object> map = new HashMap<>();
            fileName = fileName.replace("\\", "/");
            Path path = Paths.get(fileName);
            String file_Name = path.getFileName().toString(); // 2025-05-19.txt

            map.put("fileName", file_Name);
            map.put("state", 1);
            DebugLogger.info("fileName-->" + file_Name);
            String valueJson = JSON.toJSONString(map);
            String str = "{\"devID\":\"" + packet.getDevIdx() + "\",\"cmd\":\"" + Cmd.CMD_OUT_WEB_SOCKET_FILE_INFORM + "\",\"value\":" + valueJson + "}";
            DebugLogger.info(str);
            List<SysUserinfo> parentGroup = instance.getParentGroup(packet.getDevIdx());
            ResponseSendUtil.sendWsMessageToDispatcher(parentGroup, str);
            DebugLogger.info("成功");
            DebugLogger.info("0x2073-----》1");

        } else {
            //TODO  缓存添加文件数据
            DeviceInfo onlineMemberByClientId = ClientManager.getInstance().getOnlineMemberByClientId(String.valueOf(packet.getDevIdx()));
            if (onlineMemberByClientId != null) {
                onlineMemberByClientId.setFileName(fileName);
            }
            listResponse = ResponseFactory.getListResponse(Cmd.CMD_OUT_FILE_UPLOADING, (short) 0, packet.getDevIdx(), bytes);
            DebugLogger.info("0x2073-----》0");
        }
        if (listResponse != null) {
            ResponseSendUtil.writeAndFlush(listResponse, ctx);
        }

    }

    /**
     * 服务器返回提交的文件名
     *
     * @param packet
     * @throws UnsupportedEncodingException
     */
    private void uploadingFile(DecodePacket packet) throws UnsupportedEncodingException {
        String fileName = new String(packet.getBody(), StandardCharsets.UTF_8).trim();
        DebugLogger.info(packet.toString() + " -- " + fileName);
        int devIdx = packet.getDevIdx();
        byte[] listResponse = null;
        byte[] bytes = new byte[200];
        byte[] fileNamebyte = fileName.getBytes("gb2312");
        System.arraycopy(fileNamebyte, 0, bytes, 0, fileNamebyte.length);
        BDMybais instance = BDMybais.getInstance();

        //查询FTP数据  本地文件查询匹配  文件存在数据写入数据库  返回成功
        {
            FtpServer ftpServer = instance.getFtpServer(1);
            String filePath1 = ftpServer.getFtpPath() + fileName;
            String filePath = PathUtils.toSystemPath(filePath1);
            DebugLogger.info(filePath);
            boolean b = FileExistenceExample.DoesTheFileExist(filePath);
            if (!b) {
                listResponse = ResponseFactory.getListResponse(Cmd.CMD_OUT_SUBMIT_FILENAME, (short) 0, packet.getDevIdx(), bytes);
                DebugLogger.err(logger,packet.getDevIdx()+"<--packet.getDevIdx() FileExistenceExample.DoesTheFileExist is flase");
                ResponseSendUtil.writeAndFlush(listResponse, ctx);
                return;
            }
            FileMessage fileMessage = FileExistenceExample.FileInformation(filePath);
            SysDoc sysDoc = new SysDoc();
            {
                String lastFourChars = fileName.substring(fileName.length() - 4);
                DebugLogger.info(lastFourChars);
                if (lastFourChars.equalsIgnoreCase(".GPS") || lastFourChars.equalsIgnoreCase(".BDS")) {
                    sysDoc.setdDtID(4);
                } else if (lastFourChars.equalsIgnoreCase(".log") || lastFourChars.equalsIgnoreCase(".txt")) {
                    sysDoc.setdDtID(3);
                } else if (lastFourChars.equalsIgnoreCase(".mp3")) {
                    sysDoc.setdDtID(2);
                } else if (lastFourChars.equalsIgnoreCase(".mp4")) {
                    sysDoc.setdDtID(1);
                } else if (lastFourChars.equalsIgnoreCase(".jpg")) {
                    sysDoc.setdDtID(0);
                } else {
                    sysDoc.setdDtID(-1);
                }
            }
            Users users = instance.getUsers(packet.getDevIdx());
            sysDoc.setdUid(users.getuId());
            sysDoc.setdWsId(1);
            sysDoc.setdMId(3);
            sysDoc.setDdvId(packet.getDevIdx());
            sysDoc.setdShootingTime(fileMessage.getFileData());
            long timeMillis = System.currentTimeMillis();
            Date currentTime = new Date(timeMillis);
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String dateString = formatter.format(currentTime);
            sysDoc.setdUploadTime(dateString);
            sysDoc.setdFileLength(fileMessage.getFileSize());
            sysDoc.setdFilePath(fileName);
            sysDoc.setdStorePath(ftpServer.getFtpPath());

            String lastFourChars = fileName.substring(fileName.length() - 4);
            if (lastFourChars.equalsIgnoreCase(".mp4")) {
                String replacedStr = fileName.replaceAll("(?i).mp4", ".jpg");
                sysDoc.setdThumbnail(replacedStr);
                sysDoc.setdVideoType(true);
                DebugLogger.debug(logger,"filePath ffprobe file Url:"+filePath);
                long duration = MP4DurationUtil.getDuration(filePath);
                sysDoc.setdFileTime(duration * 1000);
            }
            boolean b1 = instance.setFile(sysDoc);
            DebugLogger.info(b1 + "--->instance.setFile(sysDoc)\n" + sysDoc.toString());
            if (!b1) {
                DebugLogger.err(logger,packet.getDevIdx()+"<--packet.getDevIdx()  失败--->instance.setFile(sysDoc)");

            }
        }


//        List<StaffInfo> staffData = instance.getStaffData(devIdx);
        List<SysUserinfo> parentGroup = instance.getParentGroup(devIdx);
        Map<String, Object> map = new HashMap<>();
        Path path = Paths.get(fileName);
        String file_Name = path.getFileName().toString(); // 2025-05-19.txt
        map.put("fileName", file_Name);
        Integer fileCount = instance.getFileCount(fileName);
        DebugLogger.info(fileCount + " -- >fileCount");
        if (fileCount > 0) {
            listResponse = ResponseFactory.getListResponse(Cmd.CMD_OUT_SUBMIT_FILENAME, (short) 1, packet.getDevIdx(), bytes);
            map.put("state", 1);
            String valueJson = JSON.toJSONString(map);
            String str = "{\"devID\":\"" + devIdx + "\",\"cmd\":\"" + Cmd.CMD_OUT_WEB_SOCKET_FILE_INFORM + "\",\"value\":" + valueJson + "}";

            DebugLogger.info(str);

            if (parentGroup != null && parentGroup.size() != 0) {
                //发给调度台
                ResponseSendUtil.sendWsMessageToDispatcher(parentGroup, str);
            } else {
                DebugLogger.err(logger,packet.getDevIdx()+"<--packet.getDevIdx()  uploadingFile1 parentGroup: "+parentGroup);
            }
            //TODO 清除文件缓存数据
            DeviceInfo onlineMemberByClientId = ClientManager.getInstance().getOnlineMemberByClientId(String.valueOf(packet.getDevIdx()));
            if (onlineMemberByClientId != null) {
                onlineMemberByClientId.setFileName(null);
            }


            DebugLogger.info("成功");
        } else {
            listResponse = ResponseFactory.getListResponse(Cmd.CMD_OUT_SUBMIT_FILENAME, (short) 0, packet.getDevIdx(), bytes);
            map.put("state", 0);
            String valueJson = JSON.toJSONString(map);
            String str = "{\"devID\":\"" + devIdx + "\",\"cmd\":\"" + Cmd.CMD_OUT_WEB_SOCKET_FILE_INFORM + "\",\"value\":" + valueJson + "}";

            DebugLogger.info(str);
            if (parentGroup != null && parentGroup.size() != 0) {
                ResponseSendUtil.sendWsMessageToDispatcher(parentGroup, str);
            }else {
                DebugLogger.err(logger,packet.getDevIdx()+"<--packet.getDevIdx()  uploadingFile2 parentGroup: "+parentGroup);
            }
            DebugLogger.info("失败");
        }
        if (listResponse != null) {
            ResponseSendUtil.writeAndFlush(listResponse, ctx);
        }
    }

    /**
     * 获取获取ftp服务器参数
     *
     * @param packet
     */
    private void getFtpServer(DecodePacket packet) throws UnsupportedEncodingException {

        BDMybais instance = BDMybais.getInstance();
        FtpServer ftpServer = instance.getFtpServer(1);
        DebugLogger.info(ftpServer.toString() + "------> ftpServer.toString()");
        byte[] bytes = new byte[144];
        byte[] b_ftp_ip = ftpServer.getFtpIP().getBytes("gb2312");
        byte[] b_ftp_port = ByteUtil.intToBytes(ftpServer.getFtpPort());
        byte[] b_ftp_user = ftpServer.getFtpUser().getBytes("gb2312");
        byte[] b_ftp_pswd = ftpServer.getFtpPwd().getBytes("gb2312");
        System.arraycopy(b_ftp_ip, 0, bytes, 0, b_ftp_ip.length);
        System.arraycopy(b_ftp_port, 0, bytes, 100, b_ftp_port.length);
        System.arraycopy(b_ftp_user, 0, bytes, 104, b_ftp_user.length);
        System.arraycopy(b_ftp_pswd, 0, bytes, 124, b_ftp_pswd.length);
        byte[] listResponse = ResponseFactory.getListResponse(Cmd.CMD_OUT_FTP_SERVER, (short) 0, packet.getDevIdx(), bytes);
        ResponseSendUtil.writeAndFlush(listResponse, ctx);
    }

    /**
     * 获取目标的状态及WebRTC服务器地址和端口号
     */
    private void TatgetState(DecodePacket packet) throws UnsupportedEncodingException {

        byte[] body = packet.getBody();
        byte[] AudioType = new byte[2];                 //2字节，对象类型，0 群组；1 用户1
        byte[] ID = new byte[4];                        //4 字节， 群组ID或者用户的ID
        byte[] FuncType = new byte[2];                    //2字节， 0 集群对讲；1 视频通话

        System.arraycopy(body, 0, AudioType, 0, AudioType.length);
        System.arraycopy(body, 2, ID, 0, ID.length);
        System.arraycopy(body, 6, FuncType, 0, FuncType.length);

        short ShortAudioType = ByteUtil.bytesToShort(AudioType);
        int IntID = ByteUtil.bytesToInt(ID);
        short ShortFuncType = ByteUtil.bytesToShort(FuncType);
        DebugLogger.info(IntID);
        BDMybais instance = BDMybais.getInstance();
        Users user = instance.getUser(IntID);

        if (!(user.isuIsDepartMana() || user.isuIsSysMana())) {
            if (user.getuDvId() == null || user.getuDvId() == 0) {
                DebugLogger.err(logger, packet.getDevIdx()+"<--packet.getDevIdx()  device is null  and devid is 0");
                return;
            }
        }

        WebRtc wedRtc = new WebRtc();
        wedRtc.setUserID(IntID);

        WebRtc wedRTCSeva = instance.getWedRTCSevaV2(wedRtc);
        //查询自己的信息
        Users users = instance.getUsers(packet.getDevIdx());
        byte[] bytes = ByteUtil.intToBytes(users.getuId());
        DebugLogger.info(wedRTCSeva.toString());

        VideoServer videoServerQry = null;
        if (ShortFuncType == 0) {
            videoServerQry = instance.getVideoServerQry(51);
        } else if (ShortFuncType == 1) {
            videoServerQry = instance.getVideoServerQry(51);
        }

        if (videoServerQry == null) {
            DebugLogger.err(logger, "TatgetState videoServerQry  is null");
            return;
        }

        DebugLogger.info(ctx.name() + "  发给自己  ");
        byte[] commandSend = ResponseFactory.getCommandSend(Cmd.CMD_OUT_OBJECT_WEDRTC_URL_PORT, (short) wedRTCSeva.getTalkGrade(), packet.getDevIdx(), wedRTCSeva, wedRTCSeva.getUserName(), videoServerQry, AudioType, ID, FuncType);
        ResponseSendUtil.writeAndFlush(commandSend, ctx);

        DebugLogger.info("转发给谁" + users.getuId());
        //转发给谁
        if (user.isuIsDepartMana() || user.isuIsSysMana()) {
            //TODO 走webrtc   4301
            Map<String, Object> map = new HashMap<>();
            map.put("talkGrade", 1);
            map.put("audioType", ShortAudioType);
            map.put("id", ID);
            map.put("funcType", ShortFuncType);
            map.put("audioIp", videoServerQry.getServerIP());
            map.put("audioPort", videoServerQry.getPort());
            map.put("roomId", wedRTCSeva.getRoomID());
            if (ShortAudioType == 0) {
                map.put("talkToUserName", null);

            } else if (ShortAudioType == 1) {
                map.put("talkToUserName", wedRTCSeva.getUserName());

            }

            String valueJson = JSON.toJSONString(map);
            //获取自己 调度台
//            String strUser = "[{\"devID\":\"" + packet.getDevIdx() + "\"},{\"cmd\":\"" + Cmd.CMD_OUT_WEB_SOCKET_VIDEO_CALL + "\"},{\"value\":\"" + wedRTCSeva.getTalkGrade() + "," + ShortAudioType + "," + ID + "," + FuncType + "," + videoServerQry.getServerIP() + "," + videoServerQry.getPort() + "," + wedRTCSeva.getRoomID() + "," + wedRTCSeva.getUserName()  + "\"}]";
            String strMy = "{\"devID\":\"" + packet.getDevIdx() + "\",\"cmd\":\"" + Cmd.CMD_OUT_WEB_SOCKET_VIDEO_CALL + "\",\"value\":" + valueJson + "}";

            ChannelHandlerContext webSocket = ClientManager.getInstance().getWebSocket(user.getuLoginName());
            if (webSocket != null) {
                DebugLogger.info("发送webSocket 给调度台");
                webSocket.channel().writeAndFlush(new TextWebSocketFrame(strMy));
            } else {
                DebugLogger.err(logger,"TatgetState is webSocket  null");
            }

        } else {
            ChannelHandlerContext socketClient = ClientManager.getInstance().getSocketClient(String.valueOf(user.getuDvId()));
            if (socketClient == null) {
                DebugLogger.err(logger, user.getuDvId() + "<--user.getuDvId()  Send to myself  socketClient == null");
                byte[] commandSendErr = ResponseFactory.getSend(Cmd.CMD_OUT_OBJECT_WEDRTC_URL_PORT, (short) 0, packet.getDevIdx());
                ResponseSendUtil.writeAndFlush(commandSendErr, ctx);
                return;
            }

            byte[] commandSend2 = ResponseFactory.getInformSend(Cmd.CMD_OUT_OBJECT_WEDRTC_URL_PORT, (short) wedRTCSeva.getTalkGrade(), wedRTCSeva.getDevicID(), packet.getDevIdx(), wedRTCSeva, videoServerQry, AudioType, bytes, FuncType, users.getuName());

            ResponseSendUtil.writeAndFlush(commandSend2, socketClient);
        }

    }

    /**
     * 视频通话用户列表
     */
    private void voideoList(DecodePacket packet) {
        DebugLogger.info(packet.toString());

        byte[] bytes = new byte[0];
        try {
            bytes = analysis.voideoAagreement(packet);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        byte[] groupResponse = new byte[0];
        try {
            groupResponse = ResponseFactory.getListResponse(Cmd.CMD_OUT_VIDEP_LIST, packet.getSerialNo(), packet.getDevIdx(), bytes);

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        if (bytes != null) {
            ResponseSendUtil.writeAndFlush(groupResponse, ctx);
        }
    }

    /**
     * 获取当前部门用户
     */
    private void getUsetDepList(DecodePacket packet) {

        byte[] bytes = new byte[0];
        try {
            bytes = analysis.getUserDep(packet);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        byte[] groupResponse = new byte[0];
        try {
            groupResponse = ResponseFactory.getListResponse(Cmd.CMD_OUT_VIDEP_LIST, packet.getSerialNo(), packet.getDevIdx(), bytes);

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        if (bytes != null) {
            ResponseSendUtil.writeAndFlush(groupResponse, ctx);
        } else {
            DebugLogger.err(logger, packet.getDevIdx()+"<--packet.getDevIdx()  getUsetDepList bytes==NULL");
        }
    }

    /**
     * GPS上传
     *
     * @param packet
     */
    private void uploadGPS(DecodePacket packet) {
        analysis.GPSAagreement(packet);
//        analysis.GPSAagreement2(packet);
    }

    /**
     * 发送设备端当前视频通话或者集群对讲的状态
     *
     * @param packet
     */

    private void SendEquipmentState(DecodePacket packet) {
        int devIdx = packet.getDevIdx();

        DeviceInfo onlineMemberByClientId = ClientManager.getInstance().getOnlineMemberByClientId(String.valueOf(devIdx));
        if(onlineMemberByClientId == null){
            DebugLogger.err(logger,packet.getDevIdx()+"<--packet.getDevIdx()  SendEquipmentState_onlineMemberByClientId.tostring(): "+ onlineMemberByClientId);
            return;
        }

        short serialNo = onlineMemberByClientId.getSerialNo();
        try {
            byte[] sendserialNo = ResponseFactory.getSend(Cmd.CMD_OUT_TALKBACK_MAYBE_VIDEO, serialNo, devIdx);
            ResponseSendUtil.writeAndFlush(sendserialNo, ctx);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

    }

    /**
     * 弃用
     * 获取目标的状态及服务器地址和端口号
     *
     * @param packet
     */
    @Deprecated
    private void getServerPort(DecodePacket packet) {
        Integer devIdx = packet.getDevIdx();
        if (devIdx == null || devIdx == 0) {
            DebugLogger.err(logger, packet.getDevIdx()+"<--packet.getDevIdx()  getServerPort bytes==NULL");
            return;
        }

    }

    /**
     * 设备查询IEMI是否已经注册
     */
    private void tagIMEI(DecodePacket packet) {
        byte[] body = packet.getBody();
        char[] c = new String(body).trim().toCharArray();
        for (char c1 : c) {
            System.out.print(c1);
        }
    }

    /**
     * 对讲通话人员
     */
    private void talkbackCallList(DecodePacket packet) {
        DebugLogger.info(packet.toString());
        DebugLogger.info("对讲通话人员");
        CallList(packet);
    }

    private void CallList(DecodePacket packet) {
        int devIdx = packet.getSerialNo();
        BDMybais instance = BDMybais.getInstance();
        List<GUser> getuserList = instance.getGUList(devIdx);
        byte[] bytes = new byte[0];
        try {
            bytes = analysis.userAagreement(packet, getuserList);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        byte[] groupResponse = new byte[0];
        try {
            groupResponse = ResponseFactory.getListResponse(Cmd.CMD_OUT_CAll_LIST, packet.getSerialNo(), packet.getDevIdx(), bytes);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        if (getuserList != null) {
            DebugLogger.info(getuserList);
            ResponseSendUtil.writeAndFlush(groupResponse, ctx);
        } else {
            DebugLogger.err(logger, packet.getDevIdx()+"<--packet.getDevIdx()  CallList bytes is null");
        }
    }

    /**
     * 人员列表
     * 特许处理
     */
    private void userList(DecodePacket packet) {
        byte[] bytes = new byte[0];
        try {
            int devIdx = packet.getDevIdx();
            BDMybais instance = BDMybais.getInstance();
            List<GUser> getuserList = instance.getuserList(devIdx);
            bytes = analysis.userAagreement(packet, getuserList);
            byte[] groupResponse = new byte[0];
            groupResponse = ResponseFactory.getListResponse(Cmd.CMD_OUT_TALKBACK_USER_LIST, packet.getSerialNo(), packet.getDevIdx(), bytes);
            DebugLogger.info("getuserList success:" +getuserList);
            ResponseSendUtil.writeAndFlush(groupResponse, ctx);
        } catch (UnsupportedEncodingException e) {
            logger.info("userList UnsupportedEncodingException",e);
        }


    }

    /**
     * 群组列表
     */
    private void groupList(DecodePacket packet) {
        byte[] bytes = new byte[0];
        byte[] groupResponse = new byte[0];
        try {
            bytes = analysis.groupAagreement(packet);
            groupResponse = ResponseFactory.getListResponse(Cmd.CMD_OUT_TALKBACK_GROUP_LIST, packet.getSerialNo(), packet.getDevIdx(), bytes);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        if (bytes != null) {
            ResponseSendUtil.writeAndFlush(groupResponse, ctx);
        } else {
            DebugLogger.err(logger, packet.getDevIdx()+"<--packet.getDevIdx()  groupList bytes is null");
        }

    }


    private void cancelDeviceRegister(DecodePacket packet) {
        Integer devIdx = packet.getDevIdx();
        DebugLogger.debug(logger, devIdx + "<--packet.getDevIdx(); :退出操作");
        TerminalUnLogin terminalUnLogin = new TerminalUnLogin();
        terminalUnLogin.setDev_idx(devIdx);
        terminalUnLogin.setKeepOnLine(false);
        BDMybais instance = BDMybais.getInstance();
        instance.terminalUnLogin2(terminalUnLogin);
        //通知
        byte[] commandSend = ResponseFactory.getResponse(Cmd.CMD_OUT_CANCEL_TERMINAL, (short) 1, devIdx);
        ResponseSendUtil.writeAndFlush(commandSend, ctx);
        SendOnLineStatusToMobila(packet.getDevIdx(), 0);    //tcp
        SendOnLineStatusToClient(packet.getDevIdx(), 0, 0);    // 发送到web端
        //        EnumCacheManager.INSTANCE.remove(String.valueOf(packet.getDevIdx()));
    }

    private void dealHeartbeat() {


        //心跳处理
        byte[] response = ResponseFactory.getHeartbeatResponse();
        ResponseSendUtil.writeAndFlush(response, ctx);
    }

    /**
     * 解析登录信令
     *
     * @param packet
     */
    private void dealLogin(DecodePacket packet) {

        //协议解析
        Map<String, Object> loginmap = analysis.loginAagreement(packet);
        int devIdx = packet.getDevIdx();
        int flas = (int) loginmap.get("flas");
        TerminalLogin login = (TerminalLogin) loginmap.get("class");
        if (login == null) {
            DebugLogger.err(logger, packet.getDevIdx()+"<--packet.getDevIdx()  dealLogin login is null");
            //关闭连接，返回错误信息
            byte[] response = ResponseFactory.getLoginResponse((short) flas, 0);
            ResponseSendUtil.writeAndFlush(response, ctx);
            ctx.close();
            return;
        }

        //检查是否重复登录
        ChannelHandlerContext socketClient = ClientManager.getInstance().getSocketClient(String.valueOf(login.getDev_idx()));
        if (devIdx <= 0) {//首次登录，或者是设备重启后登录

            if (socketClient != null) {//缓存已有，用户发起了冲突登录
                DebugLogger.err(logger, login.getDev_idx()+"<--getDev_idx  dealLogin  + socketClient:" + "缓存已有，用户发起了冲突登录");
                byte[] response = ResponseFactory.getLoginResponse((short) 2, 0);
                ResponseSendUtil.writeAndFlush(response, ctx);
                ctx.close();
                return;
            }
        } else {
            if (login.getDev_idx() != devIdx) {
                DebugLogger.err(logger, packet.getDevIdx()+"<--packet.getDevIdx()  dealLogin  login.getDev_idx(): "+login.getDev_idx()+" != devIdx :" + devIdx + " 登录id异常，禁止登录");
                byte[] response = ResponseFactory.getLoginResponse((short) 2, 0);
                ResponseSendUtil.writeAndFlush(response, ctx);
                ctx.close();
                return;
            }
        }

        if (socketClient != null) {
            //清除缓存
            ClientManager.getInstance().closeCtx(socketClient);
            DebugLogger.debug(logger,login.getDev_idx()+"<--getDev_idx socketClient is no null -> empty");
        }
        //检查是否查询成功
        //检查设备是否已经登陆过  还要   完善

        byte[] response = ResponseFactory.getLoginResponse((short) flas, login.getDev_idx());
        ResponseSendUtil.writeAndFlush(response, ctx);
        DebugLogger.info("dealLogin:" + login);
        ClientManager.getInstance().addSocketClient(String.valueOf(login.getDev_idx()), ctx);


        //发送服务器地址
        byte[] commandSend = new byte[0];
        try {
            commandSend = ResponseFactory.getServer(Cmd.CMD_OUT_LOG_WEDRTC_URL_PORT, (short) 1, login.getDev_idx(), login.getServerIP(), login.getServerPort());
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        DeviceInfo deviceInfo = new DeviceInfo();
        deviceInfo.setDeviceID(login.getDev_idx());
        deviceInfo.setDeviceNo(login.getDevNo());
        deviceInfo.setUserNo(login.getUserName());
        deviceInfo.setSerialNo((short) 0);
        ClientManager.getInstance().setOnlineMemberByClientId(String.valueOf(login.getDev_idx()), deviceInfo);

        ResponseSendUtil.writeAndFlush(commandSend, ctx);
        try {
            byte[] httpSend = new byte[0];
            httpSend = ResponseFactory.httpUplod(Cmd.CMD_IN_GET_HTTP_SERVER, (short) 1, login.getDev_idx(), "http://47.119.165.185:8087/sys-doc/uploadtou");
            ResponseSendUtil.writeAndFlush(httpSend, ctx);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //通知
        SendOnLineStatusToMobila(login.getDev_idx(), 1);    // 发送到手机app端
        SendOnLineStatusToClient(login.getDev_idx(), 1, login.getType());       // 发送到web端
//            EnumCacheManager.INSTANCE.put(String.valueOf(packet.getDevIdx()), login);

    }

    private void dealLogin_V2(DecodePacket packet) {

        //协议解析
        int devIdx = packet.getDevIdx();
        Map<String, Object> loginmap = analysis.loginAagreementV2(packet);
        TerminalLogin login = null;
        short flas = 0;
        flas = (short) loginmap.get("flas");
        login = (TerminalLogin) loginmap.get("class");

        if (login == null) {
            DebugLogger.err(logger, packet.getDevIdx()+"<--packet.getDevIdx()  dealLogin_V2 login is null");
            //关闭连接，返回错误信息
            byte[] response = ResponseFactory.getLoginResponse(flas, 0);
            ResponseSendUtil.writeAndFlush(response, ctx);
            ctx.close();
            return;
        }

        //检查是否重复登录
        ChannelHandlerContext socketClient = ClientManager.getInstance().getSocketClient(String.valueOf(login.getDev_idx()));
        if (devIdx <= 0) {//首次登录，或者是设备重启后登录

            if (socketClient != null) {//缓存已有，用户发起了冲突登录
                DebugLogger.err(logger, login.getDev_idx()+"<--id dealLogin_V2 socketClient:" + "缓存已有，用户发起了冲突登录");
                byte[] response = ResponseFactory.getLoginResponse((short) 2, 0);
                ResponseSendUtil.writeAndFlush(response, ctx);
                ctx.close();
                return;
            }
        } else {
            if (login.getDev_idx() != devIdx) {
                DebugLogger.err(logger, "dealLogin_V2 login.getDev_idx(): "+login.getDev_idx()+" != devIdx:" + devIdx + " 登录id异常，禁止登录");
                byte[] response = ResponseFactory.getLoginResponse((short) 2, 0);
                ResponseSendUtil.writeAndFlush(response, ctx);
                ctx.close();
                return;
            }
        }

        if (socketClient != null) {
            //清除缓存
            ClientManager.getInstance().closeCtx(socketClient);
            DebugLogger.debug(logger,devIdx + "<--packet.getDevIdx()  socketClient is no null -> empty");
        }

        // 正常登录
        byte[] response = ResponseFactory.getLoginResponse(flas, login.getDev_idx());
        ResponseSendUtil.writeAndFlush(response, ctx);
        DebugLogger.info("dealLogin_V2:" + login);
        ClientManager.getInstance().addSocketClient(String.valueOf(login.getDev_idx()), ctx);
        byte[] commandSend = new byte[0];
        try {
            commandSend = ResponseFactory.getServer(Cmd.CMD_OUT_LOG_WEDRTC_URL_PORT, (short) 1, login.getDev_idx(), login.getServerIP(), login.getServerPort());
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        DeviceInfo deviceInfo = new DeviceInfo();
        deviceInfo.setDeviceNo(login.getDevNo());
        deviceInfo.setUserNo(login.getUserName());
        deviceInfo.setSerialNo((short) 0);
        ClientManager.getInstance().setOnlineMemberByClientId(String.valueOf(login.getDev_idx()), deviceInfo);

        ResponseSendUtil.writeAndFlush(commandSend, ctx);
        try {
            byte[] httpSend = new byte[0];
            httpSend = ResponseFactory.httpUplod(Cmd.CMD_IN_GET_HTTP_SERVER, (short) 1, login.getDev_idx(), "http://47.119.165.185:8087/sys-doc/uploadtou");
            ResponseSendUtil.writeAndFlush(httpSend, ctx);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //通知
        SendOnLineStatusToMobila(login.getDev_idx(), 1);    // 发送到手机app端
        SendOnLineStatusToClient(login.getDev_idx(), 1, login.getType());       // 发送到web端
//        EnumCacheManager.INSTANCE.put(String.valueOf(packet.getDevIdx()), login);

    }

    /**
     * 发送到手机app端
     *
     * @param dev_idx
     * @param nStatus
     */
    private void SendOnLineStatusToMobila(Integer dev_idx, int nStatus) {
        byte[] commandSend = ResponseFactory.getResponse(Cmd.CMD_OUT_WEB_SOCKET_SEND_CELL, (short) nStatus, dev_idx);

    }

    /**
     * 发送到web端
     *
     * @param dev_idx
     * @param nStatus
     */
    private void SendOnLineStatusToClient(Integer dev_idx, int nStatus, int type) {
        DebugLogger.info("webSocket--服务器发送设备状态变化");
        Map<String, Object> map = new HashMap<>();
        map.put("status", nStatus);
        map.put("type", type);
        String valueJson = JSON.toJSONString(map);
        String str = "{\"devID\":\"" + dev_idx + "\",\"cmd\":\"" + Cmd.CMD_OUT_WEB_SOCKET_SEND_CELL + "\",\"value\":" + valueJson + "}";
        List<SysUserinfo> parentGroup = BDMybais.getInstance().getParentGroup(dev_idx);
        ResponseSendUtil.sendWsMessageToDispatcher(parentGroup, str);

    }

    //协议解析与协议封装
    private class ProtocolAnalysis {
        /**
         * 登入协议解析
         *
         * @param packet
         * @return
         */
        public Map<String, Object> loginAagreement(DecodePacket packet) {
            Map<String, Object> map = new HashMap<>();
            byte[] deviceNoBytes = new byte[16];//占16个字节e
            byte[] userNoBytes = new byte[16];//占16个字节
            byte[] imeiBytes = new byte[30];
            ;//30个字节
            //执行登录操作并回复客户端
            byte[] body = packet.getBody();
            //注意，拷贝的时候，不能按照实际长度分界，要按照协议来
            System.arraycopy(body, 0, deviceNoBytes, 0, deviceNoBytes.length);
            System.arraycopy(body, 16, userNoBytes, 0, userNoBytes.length);
            System.arraycopy(body, 32, imeiBytes, 0, imeiBytes.length);

            String device = new String(deviceNoBytes).trim();
            String pwd = new String(userNoBytes).trim();
            String imei = new String(imeiBytes).trim();


            //打印检查点
            {
                DebugLogger.info(new String(deviceNoBytes).trim());
                DebugLogger.info(new String(userNoBytes).trim());
                DebugLogger.info(new String(imeiBytes).trim());
            }

            TerminalLogin terminalLogin = new TerminalLogin();
            terminalLogin.setIMEI(imei);
            terminalLogin.setDevNo(device);
            terminalLogin.setSupportVideo((int) packet.getSerialNo());
            BDMybais instance = BDMybais.getInstance();
            //设备在线不做登录 (移除)
//            boolean isOnlineStatus = instance.isOnlineStatus(device);
//            if (isOnlineStatus) {
//                map.put("flas", 2);
//                map.put("class", null);
//                return map;
//            }

            //instance.terminalLogin(terminalLogin);//函数版
            TerminalLogin terminalLogin1 = instance.terminalLoginV2(terminalLogin);
            System.out.println("sql登录版本。。。。。。。。。");
//            System.out.println(terminalLogin1.toString(x));
//            Login login = BDMybais.getInstance().login(device);
            map.put("flas", 1);
            map.put("class", terminalLogin1);
            return map;
        }


        public Map<String, Object> loginAagreementV2(DecodePacket packet) {
            Map<String, Object> map = new HashMap<>();
            //解析登录报文
            byte[] deviceNoBytes = new byte[16];//占16个字节e
            byte[] userNoBytes = new byte[16];//占16个字节
            byte[] imeiBytes = new byte[30]; //30个字节
            byte[] tokenBytes = new byte[8];//8个字节
//            byte[] typeBytes = new byte[4];//4个字节
            //执行登录操作并回复客户端
            byte[] body = packet.getBody();
            //注意，拷贝的时候，不能按照实际长度分界，要按照协议来
            System.arraycopy(body, 0, deviceNoBytes, 0, deviceNoBytes.length);
            System.arraycopy(body, 16, userNoBytes, 0, userNoBytes.length);
            System.arraycopy(body, 32, imeiBytes, 0, imeiBytes.length);

            String device = new String(deviceNoBytes).trim();
            String pwd = new String(userNoBytes).trim();
            String imei = new String(imeiBytes).trim();

            System.arraycopy(body, 62, tokenBytes, 0, tokenBytes.length);
            String token = new String(tokenBytes).trim();
//            System.arraycopy(body, 70, tokenBytes, 0, typeBytes.length);
//            int type = java.nio.ByteBuffer.wrap(typeBytes).getInt();

            //打印检查点

            DebugLogger.info(logger, "loginAagreementV2" + new String(deviceNoBytes).trim());
            DebugLogger.info(logger, "loginAagreementV2" + new String(userNoBytes).trim());
            DebugLogger.info(logger, "loginAagreementV2" + new String(imeiBytes).trim());
            DebugLogger.info(logger, "loginAagreementV2" + new String(tokenBytes).trim());
//                DebugLogger.debug(new String(typeBytes).trim());

            //token校验
            if (token != null) {
                BDMybais instance = BDMybais.getInstance();
                TokenData gettoken = instance.gettoken(token);
                if (gettoken == null) {
                    map.put("flas", (short) 5);
                    map.put("class", null);
                    DebugLogger.err(logger, packet.getDevIdx() +" id " + device+" <--device loginAagreementV2 token is null");
                    return map;
                }
            }

            TerminalLogin terminalLogin = new TerminalLogin();
            terminalLogin.setIMEI(imei);
            terminalLogin.setDevNo(device);
            terminalLogin.setSupportVideo((int) packet.getSerialNo());
            terminalLogin.setType(packet.getSerialNo());
            DebugLogger.debug(logger, packet.getDevIdx() + "<--packet.getDevIdx()  loginAagreementV2 login info:" + terminalLogin);
            BDMybais instance = BDMybais.getInstance();
            //设备在线不做登录(移除)
//            boolean isOnlineStatus = instance.isOnlineStatus(device);
//            if (isOnlineStatus) {
//                map.put("flas", (short) 2);
//                map.put("class", null);
//                return map;
//            }
            TerminalLogin terminalLogin1 = instance.terminalLoginV2(terminalLogin);

            map.put("flas", (short) 1);
            map.put("class", terminalLogin1);

            return map;
        }

        public void GPSAagreement(DecodePacket packet) {

            //TODO  校验点  无
            byte[] byteNowSec = new byte[4];                //从1970-01-01 00:00:00 开始的秒数
            byte[] byteNowUsec = new byte[4];               //毫秒数
            byte[] byteUsAngle = new byte[2];                //夹角，扩大100倍
            byte[] byteUsSpeed = new byte[2];                //速度扩大了100倍,0xFFFF表示无效(千米/小时)
            byte[] byteUcLongitudeDegree = new byte[1];        //经度值之度
            byte[] byteUcLongitudeScore = new byte[1];        //经度值之分
            byte[] byteUcLatitudeDegree = new byte[1];        //纬度值之度
            byte[] byteUcLatitudeScore = new byte[1];        //纬度值之分
            byte[] byteUnLongitudeSecond = new byte[4];     //经纬度之秒,扩大了10的7次方倍
            byte[] byteUnLatitudeSecond = new byte[4];        //纬度值值秒扩大了10的7次方倍
            byte[] byteUsHigh = new byte[2];                //海拔高度0xFFFF表示无效
            byte[] byteUsTempera = new byte[2];                //温度0xFFFF表示无效(摄氏度)
            byte[] byteUcSatelliteNumber = new byte[1];        //卫星数量0xFF表示无效
            byte[] byteUcStatus = new byte[1];              //Bit0:GPS数据有效性(0:无效,1:有效)
            //Bit1:经度方向(0:东经,1:西经)
            //Bit2:纬度方向(0:南纬,1:北纬)
            //Bit3~Bit7:保留

            byte[] body = packet.getBody();
            DebugLogger.info(body.length);
            //注意，拷贝的时候，不能按照实际长度分界，要按照协议来
            System.arraycopy(body, 0, byteNowSec, 0, byteNowSec.length);
            System.arraycopy(body, 4, byteNowUsec, 0, byteNowUsec.length);
            System.arraycopy(body, 8, byteUsAngle, 0, byteUsAngle.length);
            System.arraycopy(body, 10, byteUsSpeed, 0, byteUsSpeed.length);
            System.arraycopy(body, 12, byteUcLongitudeDegree, 0, byteUcLongitudeDegree.length);
            System.arraycopy(body, 13, byteUcLongitudeScore, 0, byteUcLongitudeScore.length);
            System.arraycopy(body, 14, byteUcLatitudeDegree, 0, byteUcLatitudeDegree.length);
            System.arraycopy(body, 15, byteUcLatitudeScore, 0, byteUcLatitudeScore.length);
            System.arraycopy(body, 16, byteUnLongitudeSecond, 0, byteUnLongitudeSecond.length);
            System.arraycopy(body, 20, byteUnLatitudeSecond, 0, byteUnLatitudeSecond.length);
            System.arraycopy(body, 24, byteUsHigh, 0, byteUsHigh.length);
            System.arraycopy(body, 26, byteUsTempera, 0, byteUsTempera.length);
            System.arraycopy(body, 28, byteUcSatelliteNumber, 0, byteUcSatelliteNumber.length);
            System.arraycopy(body, 29, byteUcStatus, 0, byteUcStatus.length);
            //打印检查点
            {
                DebugLogger.info("----------------------------------------------");
                DebugLogger.info(ByteUtil.wholeToInt(byteNowSec));
                DebugLogger.info(ByteUtil.wholeToInt(byteNowUsec));
                DebugLogger.info(ByteUtil.wholeToInt(byteUsAngle));
                DebugLogger.info(ByteUtil.wholeToInt(byteUsSpeed));
                DebugLogger.info(byteUcLongitudeDegree[0]);
                DebugLogger.info(byteUcLongitudeScore[0]);
                DebugLogger.info(byteUcLatitudeDegree[0]);
                DebugLogger.info(byteUcLatitudeScore[0]);
                DebugLogger.info(ByteUtil.wholeToInt(byteUnLongitudeSecond));
                DebugLogger.info(ByteUtil.wholeToInt(byteUnLatitudeSecond));
                DebugLogger.info(ByteUtil.wholeToInt(byteUsHigh));
                DebugLogger.info(ByteUtil.wholeToInt(byteUsTempera));
                DebugLogger.info(byteUcSatelliteNumber[0]);
                DebugLogger.info(byteUcStatus[0]);
                DebugLogger.info(packet.getDevIdx());
                DebugLogger.info("----------------------------------------------");
            }


            int seconds = ByteUtil.bytesToInt(byteNowSec) - 28800;//数据库中提取的数据
            long millions = new Long(seconds).longValue() * 1000;
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String dateString = sdf.format(millions);

            DebugLogger.info("ByteUtil.wholeToInt: "+ ByteUtil.wholeToInt(byteNowSec));
            DebugLogger.info("dateString: "+dateString);

            int IntNowUsec = ByteUtil.wholeToInt(byteNowUsec);          //

            int ShortUsAngle = ByteUtil.wholeToInt(byteUsAngle);
            DebugLogger.info(ShortUsAngle);
            String direc = "0";
            if (ShortUsAngle != 0) {
                double number = ((double) ShortUsAngle / 100.0D);
                DecimalFormat decimalFormat = new DecimalFormat("#.#####");
                String result = decimalFormat.format(number);
                DebugLogger.info(result + "  result");
                if (result.length() > 5) {
                    direc = result.substring(0, 5);
                } else {
                    DebugLogger.err(logger, packet.getDevIdx()+"<--packet.getDevIdx() GPSAagreement direc is NULL and result.length()  <5 : "+ result);
                }


            }
            int ShortUsSpeed = ByteUtil.wholeToInt(byteUsSpeed);
            DebugLogger.info(ShortUsAngle);
            String speed = "0";
            if (ShortUsSpeed != 0) {
                double number = ((double) ShortUsSpeed / 100.0);
                DecimalFormat decimalFormat = new DecimalFormat("#.#####");
                String result = decimalFormat.format(number);
                if(result.length() > 5){
                    speed = result.substring(0, 5);
                } else {
                    DebugLogger.err(logger, packet.getDevIdx()+"<--packet.getDevIdx() GPSAagreement speed is NULL and result.length()  <5 : "+ result);
                }

            }
            byte UcLongitudeDegree = byteUcLongitudeDegree[0];
            byte UcLongitudeScore = byteUcLongitudeScore[0];
            byte UcLatitudeDegree = byteUcLatitudeDegree[0];
            byte UcLatitudeScore = byteUcLatitudeScore[0];
            int UnLongitudeSecond = ByteUtil.wholeToInt(byteUnLongitudeSecond);
            int UnLatitudeSecond = ByteUtil.wholeToInt(byteUnLatitudeSecond);
            int UsHigh = ByteUtil.wholeToInt(byteUsHigh);
            int UsTempera = ByteUtil.wholeToInt(byteUsTempera);
            int UcSatelliteNumber = ByteUtil.wholeToInt(byteUcSatelliteNumber);
            byte UcStatus = byteUcStatus[0];
            int devIdx = packet.getDevIdx();

            // 经度     纬度
            double wgsLon = UcLongitudeDegree + (double) UcLongitudeScore / 60.0 + ((double) UnLongitudeSecond / Math.pow(10, 7)) / 3600;
            DebugLogger.info("经度_wgsLon:" + wgsLon);
            double wgsLat = UcLatitudeDegree + (double) UcLatitudeScore / 60.0 + ((double) UnLatitudeSecond / Math.pow(10, 7)) / 3600;
            DebugLogger.info("纬度_wgsLat:" + wgsLat);
            //高度
            String altitude = "";
            if (UsHigh != 65535) {
//                altitude= String.valueOf(UsHigh).substring(0,7);
                altitude = String.valueOf(UsHigh);
            }
            //温度0xFFFF表示无效(摄氏度)
            String Tempera = "";
            if (UsTempera != 65535) {
                Tempera = String.valueOf(UsTempera).substring(0, 5);
            }
            //卫星数量0xFF表示无效

            //GPSValid


            Gps seva = new Gps();
            seva.setLon84(String.valueOf(wgsLon));
            seva.setLat84(String.valueOf(wgsLat));
            seva.setLonBD(String.valueOf(wgsLon));
            seva.setLatBD(String.valueOf(wgsLat));
            seva.setLonGCJ(String.valueOf(wgsLon));
            seva.setLatGCJ(String.valueOf(wgsLat));
            seva.setAltitude(altitude);
            seva.setSpeed(speed);
            seva.setDirec(direc);
            seva.setGPSDate(dateString);
            seva.setTempera(Tempera);
            seva.setSatelliteNumber((short) 1);
            seva.setGPSValid((byte) 1);
            seva.setDev_idx(devIdx);
            DebugLogger.info(seva.toString());
            //数据库操作
            BDMybais instance = BDMybais.getInstance();
            boolean gpsSevaV2 = instance.getGpsSevaV2(seva, devIdx);
            //转发给调度台
            Map<String, Object> map = new HashMap();
            map.put("devId", devIdx);
            map.put("time", dateString);
            switch (1) {
                case 1:// 1：84
                    map.put("lon", wgsLon);
                    map.put("lat", wgsLat);
                    break;
                case 2:// 2：百度
                    map.put("lon", wgsLon);
                    map.put("lat", wgsLon);
                    break;
                case 3://  3：高德
                    map.put("lon", wgsLon);
                    map.put("lat", wgsLon);
                    break;
                default:
                    DebugLogger.info("GPS type default " + 1);
                    // 当expression不等于任何case值时执行的代码块
                    break;
            }

            map.put("type", 1);
            map.put("height", UsHigh);
            map.put("speed", UsHigh);
            map.put("angle", ShortUsAngle);
            map.put("statellite", UcSatelliteNumber);
            map.put("isChina", 1);
            String valueJson = JSON.toJSONString(map);
            String str = "{\"devID\":\"" + devIdx + "\",\"cmd\":\"" + Cmd.CMD_OUT_WEB_SOCKET_SEND_GPS + "\",\"value\":" + valueJson + "}";
            System.err.println(str);

            List<SysUserinfo> parentGroup = instance.getParentGroup(packet.getDevIdx());
            ResponseSendUtil.sendWsMessageToDispatcher(parentGroup, str);

        }

        public void GPSAagreement2(DecodePacket packet) {
            byte[] body = packet.getBody();
            {
                DebugLogger.info("-----------------------------------------------------");
                DebugLogger.info(body.length);
                DebugLogger.info(Arrays.toString(body));
            }
            byte[] byteNowSec = new byte[4];                //从1970-01-01 00:00:00 开始的秒数
            byte[] byteNowUsec = new byte[4];               //毫秒数
            byte[] byteUsAngle = new byte[2];                //夹角，扩大100倍
            byte[] byteUsSpeed = new byte[2];                //速度扩大了100倍,0xFFFF表示无效(千米/小时)
            byte[] byteUcLongitudeDegree = new byte[1];        //经度值之度
            byte[] byteUcLongitudeScore = new byte[1];        //经度值之分
            byte[] byteUcLatitudeDegree = new byte[1];        //纬度值之度
            byte[] byteUcLatitudeScore = new byte[1];        //纬度值之分
            byte[] byteUnLongitudeSecond = new byte[4];     //经纬度之秒,扩大了10的7次方倍
            byte[] byteUnLatitudeSecond = new byte[4];        //纬度值值秒扩大了10的7次方倍
            byte[] byteUsHigh = new byte[2];                //海拔高度0xFFFF表示无效
            byte[] byteUsTempera = new byte[2];                //温度0xFFFF表示无效(摄氏度)
            byte[] byteUcSatelliteNumber = new byte[1];        //卫星数量0xFF表示无效
            byte[] byteUcStatus = new byte[1];              //Bit0:GPS数据有效性(0:无效,1:有效)
            //Bit1:经度方向(0:东经,1:西经)
            //Bit2:纬度方向(0:南纬,1:北纬)
            //Bit3~Bit7:保留

            System.arraycopy(body, 0, byteNowSec, 0, byteNowSec.length);        //从1970-01-01 00:00:00 开始的秒数
            System.arraycopy(body, 4, byteNowUsec, 0, byteNowUsec.length);      //毫秒数
            System.arraycopy(body, 8, byteUsAngle, 0, byteUsAngle.length);      //夹角，扩大100倍
            System.arraycopy(body, 10, byteUsSpeed, 0, byteUsSpeed.length);     //速度扩大了100倍,0xFFFF表示无效(千米/小时)
            System.arraycopy(body, 12, byteUcLongitudeDegree, 0, byteUcLongitudeDegree.length);
            System.arraycopy(body, 13, byteUcLongitudeScore, 0, byteUcLongitudeScore.length);
            System.arraycopy(body, 14, byteUcLatitudeDegree, 0, byteUcLatitudeDegree.length);
            System.arraycopy(body, 15, byteUcLatitudeScore, 0, byteUcLatitudeScore.length);
            System.arraycopy(body, 16, byteUnLongitudeSecond, 0, byteUnLongitudeSecond.length);
            System.arraycopy(body, 20, byteUnLatitudeSecond, 0, byteUnLatitudeSecond.length);
            System.arraycopy(body, 24, byteUsHigh, 0, byteUsHigh.length);
            System.arraycopy(body, 26, byteUsTempera, 0, byteUsTempera.length);
            System.arraycopy(body, 28, byteUcSatelliteNumber, 0, byteUcSatelliteNumber.length);
            System.arraycopy(body, 29, byteUcStatus, 0, byteUcStatus.length);


            {
                int seconds = ByteUtil.bytesToInt(byteNowSec) - 28800;//数据库中提取的数据
                int sas = seconds * 1000;
                long millions = seconds * 1000L;
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String dateString = sdf.format(millions);
                {
                    DebugLogger.info(ByteUtil.bytesToInt(byteNowSec));
                    DebugLogger.info(dateString);
                }


                DebugLogger.info("----------------------------------------------------------");
                DebugLogger.info(ByteUtil.wholeToInt(byteNowSec) + "     //从1970-01-01 00:00:00 开始的秒数");                     //从1970-01-01 00:00:00 开始的秒数
                DebugLogger.info(ByteUtil.wholeToInt(byteNowUsec) + "       //毫秒数");                     //毫秒数


                DebugLogger.info(ByteUtil.wholeToInt(byteUsAngle) + "      //夹角，扩大100倍1-01 00:00:00 开始的秒数");                     //夹角，扩大100倍1-01 00:00:00 开始的秒数
                int i = ByteUtil.wholeToInt(byteUsAngle);
                String substring = (((double) i / 1000) + "").substring(0, 5);
                DebugLogger.info(substring);
                DebugLogger.info(ByteUtil.wholeToInt(byteUsSpeed) + "     //速度扩大了100倍,0xFFFF表示无效(千米/小时)");                     //速度扩大了100倍,0xFFFF表示无效(千米/小时)
                DebugLogger.info(Arrays.toString(byteUsSpeed));
                DebugLogger.info(byteUcLongitudeDegree[0] + "     //经度值之度");                            //经度值之度
                DebugLogger.info(byteUcLongitudeDegree[0]);
                DebugLogger.info(byteUcLongitudeScore[0] + "     //经度值之分");                              //经度值之分
                DebugLogger.info(byteUcLongitudeScore[0]);
                DebugLogger.info(byteUcLatitudeDegree[0] + "      //纬度值之度");                             //纬度值之度
                DebugLogger.info(byteUcLatitudeDegree[0]);
                DebugLogger.info(byteUcLatitudeScore[0] + "       //纬度值之分");                             //纬度值之分
                DebugLogger.info(byteUcLatitudeScore[0]);
                DebugLogger.info(ByteUtil.wholeToInt(byteUnLongitudeSecond) + "   //经纬度之秒,扩大了10的7次方倍");          //经纬度之秒,扩大了10的7次方倍
                DebugLogger.info(Arrays.toString(byteUnLongitudeSecond));
                DebugLogger.info(ByteUtil.wholeToInt(byteUnLatitudeSecond) + "    //纬度值值秒扩大了10的7次方倍");           //纬度值值秒扩大了10的7次方倍
                DebugLogger.info(Arrays.toString(byteUnLatitudeSecond));
                DebugLogger.info(ByteUtil.wholeToInt(byteUsHigh) + "     //海拔高度0xFFFF表示无效");                   //海拔高度0xFFFF表示无效
                DebugLogger.info(Arrays.toString(byteUsHigh));
                DebugLogger.info(ByteUtil.wholeToInt(byteUsTempera) + "     //温度0xFFFF表示无效(摄氏度)");                //温度0xFFFF表示无效(摄氏度)
                DebugLogger.info(Arrays.toString(byteUsTempera));
                DebugLogger.info(ByteUtil.wholeToInt(byteUcSatelliteNumber) + "     //卫星数量0xFF表示无效");                            //卫星数量0xFF表示无效
                DebugLogger.info(byteUcSatelliteNumber[0]);
                DebugLogger.info(ByteUtil.wholeToInt(byteUcStatus) + "     //Bit0:GPS数据有效性(0:无效,1:有效)");                                     //Bit0:GPS数据有效性(0:无效,1:有效)
                DebugLogger.info(byteUcStatus[0]);
                DebugLogger.info("-----------------------------------------------------");
            }

        }

        public byte[] groupAagreement(DecodePacket packet) throws UnsupportedEncodingException {
            BDMybais instance = BDMybais.getInstance();
            List<Group> group = instance.getGroup(packet.getDevIdx());
            DebugLogger.info("群组列表组");
            if (group == null || group.size() <= 0) {
                DebugLogger.err(logger, packet.getDevIdx()+"<--packet.getDevIdx() groupAagreement group :"+ group);
                return null;
            }

            String groupstr = "";
            for (Iterator<Group> iterator = group.iterator(); iterator.hasNext(); ) {
                Group next = iterator.next();
                groupstr += next.getAudioGroupId() + "," + next.getAudioGroupName();
                groupstr += "|";
            }
            DebugLogger.info(groupstr);
            byte[] bytes = groupstr.getBytes("gb2312");
            String s = new String(bytes, "gb2312");
            DebugLogger.info(s + "字符串");
            return bytes;
        }

        public byte[] userAagreement(DecodePacket packet, List<GUser> getuserList) throws UnsupportedEncodingException {
            if (getuserList == null || getuserList.size() <= 0) {
                DebugLogger.err(logger, packet.getDevIdx()+"<--packet.getDevIdx()  userAagreement getuserList :"+ getuserList);
                return null;
            }
            String groupstr = "";
            for (Iterator<GUser> iterator = getuserList.iterator(); iterator.hasNext(); ) {
                GUser next = iterator.next();
                groupstr += next.getUserId() + "," + next.getuName() + "," + next.getuIsLogin() + "," + next.getuLoginType();
                groupstr += "|";
            }
            DebugLogger.info(groupstr);
            byte[] bytes = groupstr.getBytes("gb2312");
            String s = new String(bytes, "gb2312");
            DebugLogger.info(s + "字符串");
            return bytes;
        }

        public byte[] voideoAagreement(DecodePacket packet) throws UnsupportedEncodingException {
            int devIdx = packet.getDevIdx();
            BDMybais instance = BDMybais.getInstance();
            List<GUser> getuserList = instance.getuserList(devIdx);
            if (getuserList == null || getuserList.size() <= 0) {
                DebugLogger.err(logger, packet.getDevIdx()+"<--packet.getDevIdx()  voideoAagreement getuserList :"+ getuserList);
                return null;
            }
            String groupstr = "";
            for (Iterator<GUser> iterator = getuserList.iterator(); iterator.hasNext(); ) {
                GUser next = iterator.next();
                groupstr += next.getUserId() + "," + next.getuName() + "," + next.getuIsLogin() + "," + next.getSupportVideo() + "," + next.getuLoginType();
                groupstr += "|";
            }
            DebugLogger.info(groupstr);
            byte[] bytes = groupstr.getBytes("gb2312");
            String s = new String(bytes, "gb2312");
            DebugLogger.info(s + "字符串");
            return bytes;
        }

        //获取组的用户
        public byte[] getUserDep(DecodePacket packet) throws UnsupportedEncodingException {
            int devIdx = packet.getDevIdx();
            BDMybais instance = BDMybais.getInstance();
            List<GUsetDep> getUserDeps = instance.getUserDep(devIdx);
            if (getUserDeps == null || getUserDeps.size() <= 0) {
                DebugLogger.err(logger, packet.getDevIdx()+"<--packet.getDevIdx()  getUserDep getUserDeps :"+ getUserDeps);
                return null;
            }
            String groupstr = "";
            for (Iterator<GUsetDep> iterator = getUserDeps.iterator(); iterator.hasNext(); ) {
                GUsetDep next = iterator.next();
                groupstr += next.getuId() + "," + next.getuName() + "," + next.isuIsLogin() + "," + next.getuSupportVideo() + "," + next.getuLoginType();
                groupstr += "|";
            }
            DebugLogger.info(groupstr);
            byte[] bytes = groupstr.getBytes("gb2312");
            String s = new String(bytes, "gb2312");
            DebugLogger.info(s + "字符串");
            return bytes;
        }

    }


    private void emergencyCall(DecodePacket packet) throws UnsupportedEncodingException {
        SOSSave sosSave = new SOSSave();
        sosSave.setDevIdx(packet.getDevIdx());
        //数据库操作
        BDMybais instance = BDMybais.getInstance();
        instance.getSosSave(sosSave);

//        byte[] bytes = ByteUtil.intToBytes(0);
        String videoUrl = ResponseFactory.CrtRTMPUrl(packet.getDevIdx(), "stream", 1);
        byte[] rtmpByte = ByteUtil.intToBytes(1);// 4 byte, rtmp类型，0 音视频；1 视频；2 音频
        byte[] rtmpAdd = videoUrl.getBytes("gb2312");
        DebugLogger.info(videoUrl);
        byte[] bytes = new byte[132];
        System.arraycopy(rtmpByte, 0, bytes, 0, rtmpByte.length);
        System.arraycopy(rtmpAdd, 0, bytes, 4, rtmpAdd.length);
        byte[] groupResponse = new byte[0];
        try {
            groupResponse = ResponseFactory.getListResponse(Cmd.CMD_OUT_UPLOADING_RTMP, packet.getSerialNo(), packet.getDevIdx(), bytes);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        if (bytes != null) {
            ResponseSendUtil.writeAndFlush(groupResponse, ctx);
        }
    }

    private void Quit_Webrtc(DecodePacket packet) {

    }

    private void emergencyCall1(DecodePacket packet) {

        String url = new String(packet.getBody(), StandardCharsets.UTF_8);
        SOSSaveV2 sosSave = new SOSSaveV2();
        sosSave.setDevIdx(packet.getDevIdx());
        //数据库操作
        BDMybais instance = BDMybais.getInstance();
        instance.getSosSaveV2(sosSave);
        AlterSOSSave alterSOSSave = new AlterSOSSave();
        alterSOSSave.setId(sosSave.getDevicSOSID());
        alterSOSSave.setDevicType(0);
        alterSOSSave.setInfo(url);
        boolean b = instance.alterSosSaveUrl(alterSOSSave);
        if (!b) {
            DebugLogger.err(logger, packet.getDevIdx()+"<--packet.getDevIdx()  Failed to update SOS information.");//更新sos信息失败
            return;
        }

        Map<String, Object> map = new HashMap<>();
        map.put("devName", sosSave.getUserName());
        map.put("Fileurl", url);
        String valueJson = JSON.toJSONString(map);
        String str = "{\"devID\":\"" + packet.getDevIdx() + "\",\"cmd\":\"" + Cmd.CMD_OUT_WEB_SOCKET_SOS_CELL_V2 + "\",\"value\":" + valueJson + "}";

        List<SysUserinfo> parentGroup = instance.getParentGroup(packet.getDevIdx());
        ResponseSendUtil.sendWsMessageToDispatcher(parentGroup, str);
    }

    private void emergencyCall1_1(DecodePacket packet) {

        String url = new String(packet.getBody(), StandardCharsets.UTF_8);
        //数据库操作
        BDMybais instance = BDMybais.getInstance();
        SOSSaveV2 sosSaveSQL = instance.getSosSaveSQL(packet.getDevIdx());

        AlterSOSSave alterSOSSave = new AlterSOSSave();
        alterSOSSave.setId(sosSaveSQL.getDevicSOSID());
        alterSOSSave.setDevicType(0);
        alterSOSSave.setInfo(url);
        boolean b = instance.alterSosSaveUrl(alterSOSSave);
        if (!b) {
            DebugLogger.err(logger, packet.getDevIdx()+"<--packet.getDevIdx()  Failed to update SOS information.");
            return;
        }

        Map<String, Object> map = new HashMap<>();
        map.put("devName", sosSaveSQL.getUserName());
        map.put("Fileurl", url);
        String valueJson = JSON.toJSONString(map);
        String str = "{\"devID\":\"" + packet.getDevIdx() + "\",\"cmd\":\"" + Cmd.CMD_OUT_WEB_SOCKET_SOS_CELL_V2 + "\",\"value\":" + valueJson + "}";
        List<SysUserinfo> parentGroup = instance.getParentGroup(packet.getDevIdx());
        ResponseSendUtil.sendWsMessageToDispatcher(parentGroup, str);

    }

    private void emergencyCall2(DecodePacket packet) {
        SOSSave sosSave = new SOSSave();
        sosSave.setDevIdx(packet.getDevIdx());
        //数据库操作
        BDMybais instance = BDMybais.getInstance();
        instance.getSosSave(sosSave);
//        VideoServer videoServerQry = instance.getVideoServerQry(34);
        DebugLogger.info(sosSave.toString());
        String videoUrl = ResponseFactory.CrtRTMPUrl(packet.getDevIdx(), "stream", 1);
        DebugLogger.info(videoUrl);
        Map<String, Object> map = new HashMap<>();
        map.put("devName", sosSave.getUserName());
        map.put("videoUrl", videoUrl);
        String valueJson = JSON.toJSONString(map);
        String str = "{\"devID\":\"" + packet.getDevIdx() + "\",\"cmd\":\"" + Cmd.CMD_OUT_WEB_SOCKET_SOS_CELL + "\",\"value\":" + valueJson + "}";
//        String str1 = "[{\"devID\":\"" + packet.getDevIdx() + "\"},{\"cmd\":\"16393\"},{\"value\":\"" + "\"}]";
//        String str2 = "[{\"devID\":\"" + packet.getDevIdx() + "\"},{\"cmd\":\"16416\"},{\"value\":\"" + sosSave.getUserName() + "," +videoServerQry.getProtocolID()+ ","+ videoUrl + "\"}]";
//        s := '[{"devID":"' + dev_idx.tostring + '"},' + '{"cmd":"' + inttostr($4020) + '"},' + '{"value":"' + DevNo + ',' + nProtocolID.tostring + ',' + RTMPUrl + '"}]';
//        String str3 = "[{\"devID\":\"" + packet.getDevIdx() + "\"},{\"cmd\":\"16392\"},{\"value\":\"" + "\"}]";

        //开启音视频流   DeviceGetRTMPUrl
        try {
            DeviceGetRTMPUrl(packet.getDevIdx(), 0, videoUrl, "dailyInfo", true);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        List<SysUserinfo> parentGroup = instance.getParentGroup(packet.getDevIdx());
        ResponseSendUtil.sendWsMessageToDispatcher(parentGroup, str);
    }

    private void emergencyCall2_1(DecodePacket packet) {
        //数据库操作
        BDMybais instance = BDMybais.getInstance();
        SOSSaveV2 sosSaveSQL = instance.getSosSaveSQL(packet.getDevIdx());
        String  videoUrl = ResponseFactory.CrtRTMPUrl(packet.getDevIdx(), "stream", 1);
        DebugLogger.debug(logger,packet.getDevIdx() + "<--packet.getDevIdx()  emergencyCall2_1  SOS  video URL --->"+videoUrl);
        Map<String, Object> map = new HashMap<>();
        map.put("devName", sosSaveSQL.getUserName());
        map.put("videoUrl", videoUrl);
        String valueJson = JSON.toJSONString(map);
        String str = "{\"devID\":\"" + packet.getDevIdx() + "\",\"cmd\":\"" + Cmd.CMD_OUT_WEB_SOCKET_SOS_CELL + "\",\"value\":" + valueJson + "}";

        //开启音视频流   DeviceGetRTMPUrl
        try {
            DeviceGetRTMPUrl(packet.getDevIdx(), 0, videoUrl, "dailyInfo", true);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        List<SysUserinfo> parentGroup = instance.getParentGroup(packet.getDevIdx());
        ResponseSendUtil.sendWsMessageToDispatcher(parentGroup, str);
    }


    //开启音视频流
    private void DeviceGetRTMPUrl(int mydev_idx, int var, String RTMPUrl, String dailyInfo, boolean bSOS) throws UnsupportedEncodingException {
        byte[] rtmpByte = ByteUtil.intToBytes(1);// 4 byte, rtmp类型，0 音视频；1 视频；2 音频
        byte[] rtmpAdd = RTMPUrl.getBytes("gb2312");
        byte[] bytes = new byte[132];
        System.arraycopy(rtmpByte, 0, bytes, 0, rtmpByte.length);
        System.arraycopy(rtmpAdd, 0, bytes, 4, rtmpAdd.length);
        byte[] groupResponse = new byte[0];
        try {
            groupResponse = ResponseFactory.getListResponse(Cmd.CMD_OUT_UPLOADING_RTMP, (short) 1, mydev_idx, bytes);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        if (bytes != null) {
            ResponseSendUtil.writeAndFlush(groupResponse, ctx);
        }
    }


    private void messageSend(DecodePacket packet) throws UnsupportedEncodingException {
        byte[] bytes = new byte[264];
        byte[] MsgType = ByteUtil.intToBytes(0); // 信息类型；0 文本；1 照片；2 视频； 3 音频
        System.arraycopy(MsgType, 0, bytes, 0, MsgType.length);

//        char[] cr = new char[]{'1','白','小','3','摸'};
//        byte[] byte1= ByteUtil.getBytes(cr);
        String cr = "白小沫";
        byte[] byte1 = cr.getBytes("gb2312");
        System.arraycopy(byte1, 0, bytes, 4, byte1.length);

        char[] chars = ByteUtil.getChars(byte1);
        for (char aChar : chars) {
            System.out.print(aChar);
        }
//        char[] cr2 = new char[]{'1','白','2','小','3','摸','莫','魔','末','膜'};
//        byte[] byte2 = ByteUtil.getBytes(cr2);
        String cr2 = "啦啦啦德玛西亚666";
        byte[] byte2 = cr2.getBytes("gb2312");

        System.arraycopy(byte2, 0, bytes, 64, byte2.length);
        char[] char2 = ByteUtil.getChars(byte2);
        for (char aChar : char2) {
            System.out.print(aChar);
        }

//        try {
//            bytes = analysis.voideoAagreement(packet);
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }
        byte[] groupResponse = new byte[0];
        try {
            groupResponse = ResponseFactory.getListResponse(Cmd.CMD_OUT_MESSAGE_DEVICE, packet.getSerialNo(), packet.getDevIdx(), bytes);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        if (bytes != null) {
            ResponseSendUtil.writeAndFlush(groupResponse, ctx);
        }
    }


}
